/****************
 *@description:  商城订单列表   @/orderManage/mallOrder
 *@author: Xhd
 *@API: 
 *@date: 2023-11-13 09:44:38
 *@version: V1.0.0
*************************************************************************/

import React, { useState, useEffect, useRef } from "react";
import { Button, Tabs, Table, Modal } from "antd";
import { useNavigate, useLocation } from 'react-router-dom';
import TheQueryForm from '@/components/TheQueryForm';
import TheButton from '@/components/TheButton';
import Json2Excel from '@/utils/Json2Excel.js';
import { apiGetSalesReturnOrderPag } from "@/api/orderManage/index.js";
import _ from "lodash";
import { Decimal } from 'decimal.js';
import moment from 'moment';

const StoreBackAfterSaleOrder = () => {
  const navigate = useNavigate();
  const queryFormRef = useRef()
  const [searchOption, setSearchOption] = useState([
    { field: 'returnCode', label: '订单/售后单编号', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
    { field: 'time', label: '申请时间', placeholder: '请选择', required: false, rules: [], type: 'RangePicker' },
    { field: 'moneyStatus', label: '退款类型', placeholder: '请选择', required: false, rules: [], type: 'Select', options: [{ label: '全部', value: '', }, { label: '仅退款', value: 'N' }, { label: '退货退款', value: 'Y' }], defaultValue: '' },
    { field: 'memberId', label: '用户ID', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
    { field: 'memberPhone', label: '收货手机号', placeholder: '请输入', required: false, rules: [], type: 'Input', options: [], defaultValue: '' },
    { field: 'goodsQuery', label: '商品ID/名称', placeholder: '支持模糊查询', required: false, rules: [], type: 'Input', defaultValue: '' },
  ])
  const [tabData, setTabData] = useState([
    { key: "", label: '全部' },
    { key: "1", label: '退款中' },
    { key: "9", label: '退款成功' },
    { key: "4", label: '退款失败' },
    { key: "7", label: '退款取消' },
    { key: "0", label: '退款关闭' },
  ])
  const [columns, setColumns] = useState([
    {
      title: '订单编号',
      dataIndex: 'orderCode',
      key: 'orderCode',
    },
    {
      title: '售后单编号',
      dataIndex: 'returnCode',
      key: 'returnCode',
    },
    {
      title: '买家昵称',
      dataIndex: 'nickName',
      key: 'nickName',
    },
    {
      title: '退款商品',
      dataIndex: 'goodsName',
      key: 'goodsName',
      render: (text, record) => {
        let goodsSku = JSON.parse(record.goodsSkuJson)
        let arr = _.toArray(_.toArray(goodsSku).skuAttribute).map((v) => {
          return v.value
        })
        return (
          <div>
            <div>{text}</div>
            <div>{arr}</div>
          </div>
        )
      },
    },
    {
      title: '退款类型',
      dataIndex: 'moneyStatus',
      key: 'moneyStatus',
      render: (text, record) => {
        let label = ''
        switch (text) {
          case 'N':
            label = '仅退款'
            break
          case 'Y':
            label = '退货退款'
            break
        }
        return label
      },
    },
    {
      title: '实付金额（元）',
      dataIndex: 'detailPayPrice',
      key: 'detailPayPrice',
      render: (text, record) => {
        return Decimal(text).div(Decimal(100)).toNumber().toFixed(2)
      },
    },
    {
      title: '退款金额（元）',
      dataIndex: 'detailPayPrice',
      key: 'detailPayPrice',
      render: (text, record) => {
        return Decimal(text).div(Decimal(100)).toNumber().toFixed(2)
      },
    },
    {
      title: '申请时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '退款状态',
      dataIndex: 'salesStatus',
      key: 'salesStatus',
      render: (text, record) => {
        let label = ''
        switch (parseInt(text)) {
          case 1:
            label = '退款中'
            break
          case 2:
            label = '退款中，平台已同意，待寄回商品'
            break
          case 3:
            label = '退款中，商品已寄回，待平台确认'
            break
          case 4:
            label = '退款失败'
            break
          case 5:
            label = '买家退货超时自动关闭'
            break
          case 6:
            label = '卖家拒收'
            break
          case 7:
            label = '用户取消退款'
            break
          case 9:
            label = '退款成功'
            break
          case 0:
            label = '退款关闭'
            break
        }
        return label
      },
    },
    {
      title: '操作',
      key: 'operate',
      render(text, record) {
        return <TheButton type="link" 
        haspermi={['afterSales:list:detail']}
        onClick={() => {
          navigate('/orderManage/afterSaleOrder/detail', {
            state: {
              id: record.shopSalesReturnId
            }
          })
        }} >查看订单</TheButton>
      }
    },
  ])
  const [queryForm, setQueryForm] = useState({})
  const [salesStatus, setSalesStatus] = useState("")
  const [dataSource, setDataSource] = useState([])
  const [pageData, setPageData] = useState({ pageNo: 1, pageSize: 10 })
  const [total, setTotal] = useState(1000)

  //  
  useEffect(() => {
    getData(pageData)
  }, [])

  //获取数据
  let getData = async (values) => {
    await apiGetSalesReturnOrderPag({ ...values }).then(res => {
      let data = res.data.map((item, index)=>{
        item.key = index
        return item
      })
      setDataSource(data)
      setTotal(res.totalCount)
    })
  }
  //搜索
  let onFormSearch = (values) => {
    if (values && values.hasOwnProperty('time')) {
      values.createTimeStart = values.time[0].format('YYYY-MM-DD') + ' 00:00:00'
      values.createTimeEnd = values.time[1].format('YYYY-MM-DD') + ' 23:59:59'
      delete values.time
    }
    setQueryForm(values)
    getData({ pageNo: 1, pageSize: 10, salesStatus, ...values })
    setPageData({ pageNo: 1, pageSize: 10 })
  }
  //重置
  let onReset = () => {
    setQueryForm({})
    setPageData({ pageNo: 1, pageSize: 10 })
    getData({ pageNo: 1, pageSize: 10, salesStatus })
  }
  //tab切换
  let changeKey = (key) => {
    setSalesStatus(key)
    setPageData({ pageNo: 1, pageSize: 10 })
    getData({ pageNo: 1, pageSize: 10, salesStatus: key, ...queryForm })
  }
  //翻页
  let pageChange = (pageNo, pageSize) => {
    setPageData({ pageNo, pageSize })
    getData({ pageNo, pageSize, salesStatus, ...queryForm })
  }
  //导出
  let toExport = async () => {
    if (!queryForm || Object.keys(queryForm).length === 0) {
      Modal.warning({
        title: "提醒",
        content: "请选择筛选条件并查询后再导出对应的订单，暂不支持全量导出。",
        okText: "我知道了",
        onOk: () => { }
      })
      return
    }
    let res = await apiGetSalesReturnOrderPag({ ...queryForm, salesStatus, pageNo: 1, pageSize: 100, type: "Y", })
    if (res.code === 0 && res.data) {
      let data = []
      res.data.forEach(item => {
        let salesStatus = ""
        switch (parseInt(item.salesStatus)) {
          case 1:
            salesStatus = '退款中'
            break
          case 2:
            salesStatus = '退款中，平台已同意，待寄回商品'
            break
          case 3:
            salesStatus = '退款中，商品已寄回，待平台确认'
            break
          case 4:
            salesStatus = '退款失败'
            break
          case 5:
            salesStatus = '买家退货超时自动关闭'
            break
          case 6:
            salesStatus = '卖家拒收'
            break
          case 7:
            salesStatus = '用户取消退款'
            break
          case 9:
            salesStatus = '退款成功'
            break
          case 0:
            salesStatus = '退款关闭'
            break
        }
        data.push({
          orderCode: item.orderCode || '/',
          returnCode: item.returnCode || '/',
          nickName: item.nickName || '/',
          goodsName: item.goodsName || '/',
          moneyStatus: item.moneyStatus === "N" ? "仅退款" : "退货退款",
          orderPrice: Decimal(item.orderPrice).div(Decimal(100)).toNumber().toFixed(2) || '/',
          detailPayPrice: Decimal(item.detailPayPrice).div(Decimal(100)).toNumber().toFixed(2) || '/',
          returnDetailPayPrice: Decimal(item.detailPayPrice).div(Decimal(100)).toNumber().toFixed(2) || '/',
          createTime: item.createTime || '/',
          salesStatus
        })
      })
      const option = {
        fileName: '售后订单列表',
        header: [
          {
            title: '售后订单列表',
            prop: '',
            children: [
              {
                title: '订单编号',
                prop: 'orderCode',
              },
              {
                title: '退单编号',
                prop: 'returnCode',
              },
              {
                title: '买家昵称',
                prop: 'nickName',
              },
              {
                title: '退款商品',
                prop: 'goodsName',
              },
              {
                title: '退款类型',
                prop: 'moneyStatus',
              },
              {
                title: '订单金额（元）',
                prop: 'orderPrice',
                valueType: 'number'
              },
              {
                title: '实付金额（元）',
                prop: 'detailPayPrice',
                valueType: 'number'
              },
              {
                title: '退款金额（元）',
                prop: 'returnDetailPayPrice',
                valueType: 'number'
              },
              {
                title: '申请时间',
                prop: 'createTime',
              },
              {
                title: '退款状态',
                prop: 'salesStatus',
              },
            ]
          },
        ],
        dataSource: data
      }
      Json2Excel(option)
    }
  }

  return (
    <div className={'wrap-box wrap-box-content'}>
      <TheQueryForm ref={queryFormRef} show={true} option={searchOption}
        onGetValues={(values) => onFormSearch(values)}
        onReset={(values) => onReset(values)}
      >
        <TheButton size="middle" haspermi={['afterSales:list:export']} onClick={() => toExport()} type="default">导出</TheButton>
      </TheQueryForm>
      <Tabs defaultActiveKey="" items={tabData} onChange={changeKey} >
      </Tabs>
      <Table
        bordered
        columns={columns}
        dataSource={dataSource}
        scroll={{ x: "", y: '48vh' }}
        pagination={{
          position: ['bottomCenter'],
          current: pageData.pageNo,
          pageSize: pageData.pageSize,
          total: total,
          onChange: pageChange,
          showSizeChanger: false
        }}
      ></Table>
    </div>
  )
};

export default StoreBackAfterSaleOrder